<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form inline>
      <el-form-item label="组件名称">
        <el-input
          clearable
          placeholder="请输入组件名称"
          v-model="searchForm.cubeName"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="组件类型">
        <el-select
          v-model="searchForm.type"
          placeholder="请选择组件类型"
          clearable
          style="width: 150px"
        >
          <el-option label="普通" value="normal" />
          <el-option label="轮播" value="carousel" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch" size="small">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset" size="small">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
        <el-button type="primary" @click="handleAdd" size="small">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <BaseTable
      :table-data="cubeList"
      :table-columns="tableColumns"
      :table-loading="loading"
      :page-num="pageInfo.pageNum"
      :page-size="pageInfo.pageSize"
      :total="pageInfo.total"
      :options="tableOptions"
      @update:pageNum="pageInfo.pageNum = $event"
      @update:pageSize="pageInfo.pageSize = $event"
      @turnOn="loadCubeList"
    >
      <!-- 组件类型插槽 -->
      <template #type="{ row }">
        <el-tag :type="row.type === 'normal' ? 'primary' : 'success'">
          {{ row.type === 'normal' ? '普通' : '轮播' }}
        </el-tag>
      </template>

      <!-- 图片插槽 -->
       <template #imageUrl="{ row }">
         <el-image
           v-if="row.imageUrl"
           :src="row.imageUrl"
           style="width: 60px; height: 60px"
           :preview-src-list="[row.imageUrl]"
           fit="cover"
         />
         <span v-else>暂无图片</span>
       </template>

       <!-- 创建时间插槽 -->
       <template #createdAt="{ row }">
         <span v-if="row.createdAt">
           {{ new Date(row.createdAt).toLocaleString() }}
         </span>
         <span v-else>--</span>
       </template>

       <!-- 操作插槽 -->
      <template #operation="{ row }">
        <el-button size="small" type="primary" text @click="handleEdit(row)">
          编辑
        </el-button>
        <el-button size="small" type="danger" text @click="handleDelete(row)">
          删除
        </el-button>
      </template>
    </BaseTable>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import BaseTable from '@/components/BaseTable/index.vue'
import {
  getCubeList,
  createCube,
  updateCube,
  deleteCube,
  batchDeleteCubes
} from '@/api/webbase'
import { useRouter } from 'vue-router'

// 立方体组件数据类型定义
interface CubeItem {
  _id: string
  cubeName: string
  bindFileName: string
  bindComponentString: string
  bindFileCache?: string
  type?: string
  templateId?: string
  templateName?: string
  imageUrl?: string
  createdAt?: Date
  updatedAt?: Date
}

const router = useRouter()

// 查询表单
const searchForm = reactive({
  cubeName: '',
  type: ''
})

// 分页信息
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0
})

// 立方体组件数据
const cubeList = ref<CubeItem[]>([])
const loading = ref(false)

// 表格配置
const tableOptions = {
  stripe: true,
  showSelect: false,
  showOrder: true,
  showOption: true,
  optionWidth: 150
}

// 表格列配置
const tableColumns = [
  {
    prop: 'cubeName',
    label: '组件名称',
    width: 180
  },
  {
    prop: 'bindFileName',
    label: '绑定文件名',
    width: 200,
    showOverflowTooltip: true
  },
  {
    prop: 'type',
    label: '组件类型',
    width: 120,
    slotable: true
  },
  {
    prop: 'templateName',
    label: '绑定模板名称',
    width: 150,
    showOverflowTooltip: true
  },
  {
    prop: 'imageUrl',
    label: '预览图',
    width: 100,
    slotable: true
  },
  {
    prop: 'createdAt',
    label: '创建时间',
    width: 180,
    slotable: true
  }
]

/**
 * 分页查询立方体组件列表
 */
const loadCubeList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      pageNum: pageInfo.pageNum,
      pageSize: pageInfo.pageSize
    }
    const res = await getCubeList(params)
    if (res.data) {
      cubeList.value = (res.data as { rows?: CubeItem[]; list?: CubeItem[] }).rows ||
                       (res.data as { rows?: CubeItem[]; list?: CubeItem[] }).list ||
                       []
      pageInfo.total = ((res.data as any).total as number) || 0
    }
    console.log('立方体组件列表:', res.data)
  } catch (error) {
    console.error('获取立方体组件列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索处理
 */
const handleSearch = () => {
  pageInfo.pageNum = 1
  loadCubeList()
}

/**
 * 重置处理
 */
const handleReset = () => {
  searchForm.cubeName = ''
  searchForm.type = ''
  pageInfo.pageNum = 1
  loadCubeList()
}

/**
 * 新增处理
 */
const handleAdd = () => {
  router.push({ path: '/add-modules' })
}

/**
 * 编辑处理
 * @param row 行数据
 */
const handleEdit = (row: CubeItem) => {
  router.push({ path: '/add-modules', query: { id: row._id } })
}

/**
 * 删除处理
 * @param row 行数据
 */
const handleDelete = (row: CubeItem) => {
  ElMessageBox.confirm(
    `确定要删除组件 "${row.cubeName}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteCube(row._id)
      ElMessage.success('删除成功')
      loadCubeList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadCubeList()
})
</script>

<style scoped lang="less">
.qiankun_container {
  height: 80vh;
  width: 80vw;
}
</style>
<!-- 1. 模块存在前端Components中，通过微前端显示。后端存记录和对应的图片。删除时删除对应的模块和图片 -->
 <!-- 2.  -->
